import axios from 'axios'
import Cookies from 'js-cookie'
import store, { actionCreators } from '../store'
import { TOKEN_KEY } from '../constants'

const BASE_URL = '/'
// const BASE_URL = '//47.98.61.156:8080/'
axios.defaults.baseURL = BASE_URL
axios.defaults.withCredentials = true

axios.interceptors.request.use(config => {
  config.headers = Object.assign(config.headers, {
    'X-Requested-With': 'XMLHttpRequest',
    token: Cookies.get(TOKEN_KEY)
  })
  return config
})

axios.interceptors.response.use(response => {
  const data = response.data
  if (data.code && [1000201, 1000202, 1000203].indexOf(data.code) > -1) {
    Cookies.remove(TOKEN_KEY)
    store.dispatch(actionCreators.setLoginStatus(false))
    setTimeout(() => {
      window.location.href = '/#login'
    })
  }
  if (data.code && data.code === 1000204 && location.pathname !== '/') {
    window.location.href = '/'
  }
  return data
})

export const BACKEND_BASE_URL = BASE_URL

export const get = (url, params, options) => {
  return axios.get(url, { params, ...options })
}

export const post = (url, data, options) => {
  return axios.post(url, data, options)
}
